package project.dade.cn.bst.activity;

import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.squareup.okhttp.Request;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.InjectView;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import project.dade.cn.bst.R;
import project.dade.cn.bst.adapter.base.SearchAdapter;
import project.dade.cn.bst.base.ZJPBaseBarActivity;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.model.BaseRequestsModel;
import project.dade.cn.bst.model.IndexInfoHots;
import project.dade.cn.bst.network.callback.ResultCallback;
import project.dade.cn.bst.network.request.OkHttpRequest;
import project.dade.cn.bst.utils.AppUtil;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.MarginDecoration;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.ToastUtil;
import project.dade.cn.bst.views.EmptyLayout;


/**
 * Created by vain zhou on 2015/11/2.
 */
public class SearchActivity extends ZJPBaseBarActivity implements View.OnClickListener,BGARefreshLayout.BGARefreshLayoutDelegate{
    @InjectView(R.id.iv_erwei)
    ImageView finish;
    @InjectView(R.id.btn_right)
    TextView search;
    @InjectView(R.id.list)
    RecyclerView recyclerView;
    @InjectView(R.id.error_layout)
    EmptyLayout emptyLayout;
    @InjectView(R.id.et_search)
    EditText editText;
    private SearchAdapter Adapter;
    @InjectView(R.id.rl_recyclerview_refresh)
    BGARefreshLayout mRefreshLayout;
    private int page = 1;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        search.setOnClickListener(this);
        GridLayoutManager layoutManager = new GridLayoutManager(this,2);
        layoutManager.setOrientation(GridLayoutManager.VERTICAL);
        recyclerView.addItemDecoration(new MarginDecoration(this));
        Adapter = new SearchAdapter(recyclerView);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(Adapter);
        mRefreshLayout.setDelegate(this);
        mRefreshLayout.setRefreshViewHolder(new BGANormalRefreshViewHolder(SearchActivity.this, true));
        finish.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_right:
                if(TextUtils.isEmpty(editText.getText().toString().trim())){

                    ToastUtil.showShort(SearchActivity.this, "输入您想要搜索的商品");
                }else {

                    initRequest();
                }
                break;
            case R.id.iv_erwei:
                finish();
                break;
        }

    }
    private void initRequest() {
        if (AppUtil.isNetworkAvailable(SearchActivity.this)) {
            requestGetSearch();
        } else {
            emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        }
    }

    private void requestGetSearch() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("keyWord", editText.getText().toString().trim());
        params.put("PageIndex",page+"");
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Search).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        mRefreshLayout.endRefreshing();
                        ToastUtil.showShort(SearchActivity.this, "网络相应失败请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
                        mRefreshLayout.endRefreshing();
                        LogUtil.i(TAG, "提交收获地址：" + response);
                            BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                            LogUtil.i(TAG, "提交收获地址1：" + model.getData());
                            if (model != null && model.getResult() == 0) {

                                    //获取请求成功
                                    List<IndexInfoHots> Dates = new ArrayList<>();
                                    Dates = JSON.parseArray(model.getData(), IndexInfoHots.class);
                                    LogUtil.i(TAG, "获取的地址：" + Dates);
                                    Adapter.setDatas(Dates);

                            }else  if(model.getResult() == 1) {
                                emptyLayout.setErrorType(EmptyLayout.NODATA);
                                emptyLayout.setErrorMessage("暂无内容");
                            }

                         else {
                                mRefreshLayout.endRefreshing();
                            ToastUtil.showShort(SearchActivity.this, NetRequestUtil.requestsError(response, "搜索结果"));

                        }
                    }

                });


    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        if (AppUtil.isNetworkAvailable(SearchActivity.this)) {
            page=1;
            requestGetSearch();
        } else {
            emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        }

    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        if (AppUtil.isNetworkAvailable(this)) {
            page++;
            requestGetMoreSearch();
        } else {
            mRefreshLayout.endLoadingMore();
            Snackbar.make(recyclerView, R.string.tips_network_error, Snackbar.LENGTH_SHORT).show();
        }
        return true;
    }

    private void requestGetMoreSearch() {

            final HashMap<String, String> params = new HashMap<String, String>();
            params.put("keyWord", editText.getText().toString().trim());
            params.put("PageIndex",page+"");
            new OkHttpRequest.Builder()
                    .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Search).params(params)
                    .post(new ResultCallback<String>() {
                        @Override
                        public void onError(Request request, Exception e) {
                            mRefreshLayout.endLoadingMore();
                            ToastUtil.showShort(SearchActivity.this, "网络相应失败请稍后再试");
                        }

                        @Override
                        public void onResponse(String response) {
                            mRefreshLayout.endLoadingMore();
                            LogUtil.i(TAG, "提交收获地址：" + response);
                            BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                            LogUtil.i(TAG, "提交收获地址1：" + model.getData());
                            if (model != null && model.getResult() == 0) {

                                //获取请求成功
                                List<IndexInfoHots> Dates = new ArrayList<>();
                                Dates = JSON.parseArray(model.getData(), IndexInfoHots.class);
                                LogUtil.i(TAG, "获取的地址：" + Dates);
                                Adapter.addMoreDatas(Dates);
                            }else  if(model.getResult() == 1) {
                                ToastUtil.showShort(SearchActivity.this, "已经没了哦");
                                page--;
                            }

                            else {
                                mRefreshLayout.endLoadingMore();
                                ToastUtil.showShort(SearchActivity.this, NetRequestUtil.requestsError(response, "搜索结果"));

                            }
                        }

                    });


        }
}
